<template>
  <div class="option-wrapper">
    <div class="option-main">
      <a-form layout="vertical" ref="formRef" :model="formState" :rules="rules" @finish="handleSubmit">
        <div class="option-column">
          <div class="column-title">客户基础信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="客户名称" name="name">
                <a-input v-model:value="formState.name" placeholder="请输入客户名称" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="客户编号" name="no">
                <a-input :disabled="true" v-model:value="formState.no" placeholder="(自动生成)" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="客户分类" name="customer_type_id">
                <a-select v-model:value="formState.customer_type_id" placeholder="请选择分类">
                  <a-select-option v-for="(item, index) in classOptions" :key="index" :value="item.value">{{ item.text
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="状态">
                <a-select v-model:value="formState.customer_status_id" placeholder="请选择状态">
                  <a-select-option v-for="(item, index) in statusOptions" :key="index" :value="item.value">{{ item.text
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="所在地区">
                <a-cascader v-model:value="formState.city_id" :options="zoneoList" placeholder="请选择地区" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="上传LOGO">
                <a-upload :max-count="1" v-model:file-list="fileList" :show-upload-list="false" list-type="picture-card"
                  :customRequest="handleCustomRequest" @change="handleChange">
                  <div v-if="formState.logo">
                    <img :src="formState.logo" style="max-width: 100px; max-height: 100px;vertical-align: top;"></img>
                  </div>
                  <div v-else>
                    <PlusOutlined />
                  </div>
                </a-upload>
              </a-form-item>
            </div>
          </div>
        </div>
        <div class="option-column">
          <div class="column-title">联系人信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="姓名">
                <a-input v-model:value="formState.contacts.name" placeholder="请输入联系人姓名" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="职务">
                <a-input v-model:value="formState.contacts.duty" placeholder="请输入职务" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="手机号">
                <a-input v-model:value="formState.contacts.mobile" placeholder="请输入联系人手机号" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="联系电话">
                <a-input v-model:value="formState.contacts.tel" placeholder="请输入联系人电话" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="电子邮箱">
                <a-input v-model:value="formState.contacts.email" placeholder="请输入联系人电子邮箱" />
              </a-form-item>
            </div>
          </div>
        </div>
        <div class="option-column">
          <div class="column-title">经销商信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="经销商">
                <a-select v-model:value="formState.dealer_id" placeholder="请选择经销商">
                  <a-select-option v-for="(item, index) in dealerList" :key="index" :value="item.dealer_id">{{ item.name
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="销售员">
                <a-input v-model:value="formState.sales_name" placeholder="请输入销售员姓名" />
              </a-form-item>
            </div>
          </div>
        </div>
        <div class="option-footer">
          <a-button class="opt-btn" @click="resetForm">取消</a-button>
          <a-button class="opt-btn" type="primary" htmlType="submit">保存</a-button>
        </div>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import router from "@/routers";
import { ref, computed, onMounted } from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import API from "@/api/operation";
import SAPI from "@/api/system";
import { useRoute } from "vue-router";
import { message } from "ant-design-vue";
import { getCityId } from "@/utils/city.ts";
import systemApi from "@/api/system";
const route = useRoute();
//获取当前url参数
const query = computed(() => route.query);
const formState = ref({
  model_files: [],
  name: "",
  no: "",
  customer_type_id: null,
  customer_status_id: null,
  city_id: [],
  logo: "",
  contacts: {
    name: "",
    duty: "",
    mobile: "",
    tel: "",
    email: "",
  },
  dealer_id: "",
  sales_name: "",
});
const classOptions = ref();
const getTypeOptions = async () => {
  const res = await API.CustomerTypeOptions({});
  classOptions.value = res;
};
const zoneoList = ref([]);
const getZoneData = async () => {
  const res = await SAPI.CityCityTree();
  zoneoList.value = res;
};
const statusOptions = ref();
const getStatusOptions = async () => {
  const res = await API.CustomerStatusOptions({});
  statusOptions.value = res;
};
const dealerList = ref();
const getDealerOptions = async () => {
  const res = await API.DealerOptions({});
  dealerList.value = res;
};
onMounted(async () => {
  await getTypeOptions();
  await getZoneData();
  await getStatusOptions();
  await getDealerOptions();
  if (query.value.id) {
    getData();
  }
});
const fileList = ref([]);
const handleCustomRequest = async (options) => {
  const { file, onSuccess, onError } = options;
  try {
    const response = await systemApi.FileUpload(file);
    console.log(response, 'response')

    if (response && response.url) {
      onSuccess(response, file);
    } else {
      onError(new Error('上传失败'));
    }
  } catch (error) {
    console.error('文件上传失败:', error);
    onError(error);
  }
};
const handleChange = (info) => {
  const status = info.file.status;
  if (status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (status === "done") {
    message.success(`${info.file.name} 文件上传成功`);
    // 将文件对象添加到 model_files 数组
    if (info.file.response && info.file.response.url) {
      formState.value.model_files.push({
        ...info.file,
        url: info.file.response.url
      });
      console.log('上传成功后的model_files数据:', formState.value.model_files);
    }
  } else if (status === "error") {
    message.error(`${info.file.name} 文件上传失败`);
  }
};
const rules = ref({
  name: [
    {
      required: true,
      message: "请输入客户名称",
      trigger: "blur",
    },
  ],
  class: [
    {
      required: true,
      message: "请选择客户分类",
      trigger: "change",
    },
  ],
});
const formRef = ref(null);
const handleSubmit = (values) => {
  formRef.value.validate().then(async () => {
    console.log(formState.value);
    if (query.value.id) {
      //编辑
      const res = await API.CustomerUpdate({
        name: formState.value.name,
        no: formState.value.no,
        customer_type_id: formState.value.customer_type_id,
        customer_status_id: formState.value.customer_status_id,
        city_id: formState.value.city_id[1],
        logo: formState.value.model_files.length > 0 ? formState.value.model_files[0].url : formState.value.logo,
        customer_contacts: formState.value.contacts,
        dealer_id: formState.value.dealer_id,
        sales_name: formState.value.sales_name,
        customer_id: query.value.id,

      });
      console.log(res);
      if (res) {
        formRef.value.resetFields();
        //提示编辑成功
        message.success("编辑成功");
        //后退
        router.go(-1);
      }
    } else {
      //新增
      const args = {
        ...formState.value,
        enabled: true,
        city_id: formState.value.city_id[1],
        create_time: new Date().getTime(),
        logo: formState.value.model_files && formState.value.model_files.length > 0 ? formState.value.model_files[0].url : formState.value.logo
      };
      const res = await API.CustomerCreateCustomer(args);
      console.log(res);
      if (res) {
        formRef.value.resetFields();
        //提示新增成功
        message.success("新增成功");
        //后退
        router.go(-1);
      }
    }
  });
};
const resetForm = () => {
  formState.value = { contacts: {} };
  router.go(-1);
};

const getData = async () => {
  let params = {
    customer_id: query.value.id,
  };
  const res = await API.CustomerFetchModel(params);

  formState.value = {
    ...res,
    model_files: formState.value.model_files || [],
    contacts: res.contacts || {
      name: "",
      duty: "",
      mobile: "",
      tel: "",
      email: "",
    },
    city_id: getCityId(zoneoList.value, res.city_id)
  };
};


</script>
